package com.life.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.life.mapper.ArticleMapper;
import com.life.pojo.dto.ArticleDTO;
import com.life.pojo.dto.ArticleQueryDTO;
import com.life.pojo.entity.Article;
import com.life.pojo.vo.ArticleVO;
import com.life.result.PageResult;
import com.life.result.Result;
import com.life.service.ArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/article")
@Api(tags = "文章管理")
@Slf4j
public class ArticleController {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleService articleService;

    /**
     * 分页查询文章
     * @return
     */
    @GetMapping
    @ApiOperation("分页查询文章")
    public Result<PageResult> pageQuery(ArticleQueryDTO articleQueryDTO) {
        log.info("分页查询文章：{}", articleQueryDTO);
        if(articleQueryDTO.getPageNum() == null || articleQueryDTO.getPageSize() == null) {
            articleQueryDTO.setPageNum(1);
            articleQueryDTO.setPageSize(10);
        }
        PageHelper.startPage(articleQueryDTO.getPageNum(), articleQueryDTO.getPageSize());
        Page<ArticleVO> page = articleMapper.pageQueryByAdmin(articleQueryDTO);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return Result.success(pageResult);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id获取文章")
    public Result<ArticleVO> getArticleById(@PathVariable Long id) {
        log.info("根据id获取文章: {}", id);
        ArticleVO article = articleService.getArticleById(id);
        return Result.success(article);
    }

    @PostMapping
    @ApiOperation("新增文章")
    public Result<String> saveArticle(@RequestBody ArticleDTO articleDTO) {
        log.info("新增文章: {}", articleDTO);
        Article article = new Article();
        BeanUtils.copyProperties(articleDTO, article);
        articleMapper.insertArticle(article);
        return Result.success();
    }

    @PutMapping
    @ApiOperation("更新文章")
    public Result<String> updateArticle(@RequestBody ArticleDTO articleDTO) {
        log.info("更新文章: {}", articleDTO);
        Article article = new Article();
        BeanUtils.copyProperties(articleDTO, article);
        articleMapper.updateArticle(article);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除文章")
    public Result<String> deleteArticle(@PathVariable Long id) {
        log.info("删除文章: {}", id);
        articleMapper.deleteArticle(id);
        return Result.success();
    }
}
